#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int echopin=3; // echo接3端口
const int trigpin=2; // trig接2端口
int total = 0; 
int old_total = total;
int down = 0 ;

void setup()
{
  lcd.begin();
  lcd.backlight();
  lcd.print("Push-ups:");
  Serial.begin(9600);  
  pinMode(echopin,INPUT_FAST); //设定echo为输入模式
  pinMode(trigpin,OUTPUT_FAST);//设定trig为输出模式
  Serial.println("Ultrasonic sensor:");
}
void loop()
{
  digitalWrite(trigpin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigpin,LOW); //发一个10ms的高脉冲去触发TrigPin
  float distance = pulseIn(echopin,HIGH);//接收高电平时间
  distance = distance/58.0;//计算距离
  //Serial.print(distance);  //输出距离
  //Serial.print("cm");  //输出单位
  if(distance < 5)
  {
    down = 1;
  }
  if(distance >= 15 && down == 1)
  {
    total = total + 1;
    down = 0;
    
  }
  if (total != old_total){
    lcd.clear();//清屏
  }
  //Serial.print(total);
  //Serial.println();
  lcd.setCursor(0,0);//光标从这里开始
  lcd.print("Push-ups:");
  lcd.setCursor(0,1);//显示个数
  lcd.print(total);
  old_total = total;
  delay(100);   //循环间隔
  
}
